//按用户自定义查询条件查询，调用treegird的load方法，传递name查询条件
function QueryData() {
	var selectId = typeof currentSelectRowId != 'undefined' ? currentSelectRowId : "";
	loadDataGrid(selectId);
}
// 清除查询条件
function ClearQuery() {
	$(theArgFormID).find("input").val("");
}

$(function() {
	if(typeof(customOnLoad)=="function") {
    	customOnLoad();
    }
	
	$('body').append(
	'<div id="myWindow" class="easyui-dialog" closed="true"></div>');

	$('#myWindow').window({
	onBeforeClose : function() { // 当面板关闭之前触发的事件
		$('#myWindow').window('close', true);
		// QueryData();
	}
	});
	
	/**
	 * 指定位置显示$.messager.show options $.messager.show的options param =
	 * {left,top,right,bottom}
	 */
	$.extend($.messager, {
		showBySite : function(options, param) {
			var site = $.extend({
				left : "",
				top : "",
				right : 0,
				bottom : -document.body.scrollTop
						- document.documentElement.scrollTop
			}, param || {});
			var win = $("body > div .messager-body");
			if (win.length <= 0)
				$.messager.show(options);
			win = $("body > div .messager-body");
			win.window("window").css({
				left : site.left,
				top : site.top,
				right : site.right,
				zIndex : $.fn.window.defaults.zIndex++,
				bottom : site.bottom
			});
		}
	});

	$(theGridID).treegrid(
			{
				title : theGridTitle==''?'': theGridTitle+ "数据列表",
				iconCls : '',
				align : 'center',
				width : document.body.clientWidth,
				height : document.body.clientHeight,
				fit : true,
				nowrap : false,
				striped : true,
				collapsible : false,
				url : '',
				sortName : theSortName,
				sortOrder : theSortOrder,
				remoteSort : false,
				idField : theIdField,
				treeField : theTreeIdField,
				loadMsg : '正在努力加载数据，请稍后...',
				singleSelect : true,// 是否单选
				pagination : false,// 是否显示分页工具栏
				rownumbers : false,
				animate : true,
				showFooter : true,

				frozenColumns : [ [ {
					title : '分类ID',
					field : theIdField,
					width : 0,
					hidden : true
				} ] ],

				columns : theColumns,

				toolbar : theToolbar,
				onClickRow : function(row){
					if (typeof (customOnClickRow) == "function") {
						customOnClickRow(row);
					}
					
				},
				onLoadSuccess : function() {
					// 加载完数据关闭等待的div
					$(theGridID).treegrid('loaded');
				}

			});
	
	$.extend($.fn.treegrid.defaults.view, {
		onAfterRender : function(dd) {
			$(theArgFormID).appendTo('.datagrid-toolbar');
			resize();
		}
	});
	
	loadDataGrid();

	if (typeof (custominit) == "function") {
		custominit();
	}
	
});


$(window).resize(function() {
	$(theGridID).treegrid('resize', {
		width : function() {
			return document.body.clientWidth;
		},
		height : function() {
			return document.body.clientHeight;
		},
	});
});

function resize() {
	$(theGridID).treegrid('resize', {
		width : document.body.clientWidth,
		height : document.body.clientHeight
	});
}

$.fn.serializeObject = function() {
	var o = {};
	var a = this.serializeArray();
	$.each(a, function() {
		if (o[this.name]) {
			if (!o[this.name].push) {
				o[this.name] = [ o[this.name] ];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

function loading() {
	$(theGridID).treegrid('loading');// 打开等待div
}

function loaded() {
	$(theGridID).treegrid('loaded');
}

function loadDataGrid(id) {
	$(theGridID).treegrid('loading');// 打开等待div
	var queryCondition = JSON.stringify($(theArgFormID).serializeObject());
	var gridOpts = $(theGridID).treegrid('options');
	var queryParams = [ {
		pageNumber : gridOpts.pageNumber,
		pageSize : gridOpts.pageSize,
		sortName : gridOpts.sortName,
		sortOrder : gridOpts.sortOrder
	} ];
	queryParams = JSON.stringify(queryParams);
	var params = "{queryParams:" + queryParams + ",queryCondition:["
			+ queryCondition + "]}";
	// alert(params);
	if(typeof(ClearData)=="function") {
		ClearData();
	}
	else{
		var roots = $(theGridID).treegrid('getRoots');
		for ( var i = roots.length - 1; i >= 0; i--) {
			$(theGridID).treegrid('remove', roots[i].classId);
		}
	}

	$.ajax({
		type : "POST", // 访问WebService使用Post方式请求
		contentType : "application/json; charset=utf-8",
		url : postURL, // 调用WebService的地址和方法名称组合 ---- WsURL/方法名
		data : params, // 这里是要传递的参数，格式为 data: "{paraName:paraValue}",下面将会看到
		dataType : 'json', // WebService 会返回Json类
		success : function(result) { // 回调函数，result，返回值

			if (result.rows.length == 0) {
				// $.messager.alert("结果", "没有数据!", "info", null);
				$(theArgFormID).appendTo('.datagrid-toolbar');
				resize();
				//showMsg('操作提示', '查询结果没有数据!');
			} else {
				$(theGridID).treegrid('loadData', result.rows);
				var selectId = id === undefined ?"":id;
				if (selectId) {
					select(selectId);
				}
			}

			$(theGridID).treegrid('loaded');

		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			// alert(errorThrown);
			window.showMsg('操作提示', '查询失败，请重新登录！');
			$(theGridID).treegrid('loaded');
			window.location.reload();
		}
	});
}

function doDelete(Ids) {
	$.messager.confirm(theGridTitle + '删除确认', '确定要删除吗?', function(row) {
		if (row) {
			$(theGridID).datagrid('loading');// 打开等待div
			$.ajax({
				url : deleteURL,
				type : "post",
				cache : false,
				data : "ids=" + Ids,
				success : function(data) {
					if (data == "success") {
						// alert("删除"+theGridTitle+"成功!");
						// $.messager.alert('删除', '操作成功!');
						showMsg('操作提示', '删除' + theGridTitle + '成功!');
						// loadDataGrid();
						/*
						for ( var i = 0; i < Ids.length; i++) {
							$(theGridID).treegrid('remove', Ids[i]);
						}
						*/
						if(typeof currentSelectRowId != 'undefined'){
							currentSelectRowId = "";
						}
						
						QueryData();
						if(typeof(parent.window.QueryData)=="function") {
							parent.window.QueryData();
						}
					} else {
						$.messager.alert('操作提示', '删除' + theGridTitle + '操作失败!',
								'error');
					}
					$(theGridID).treegrid('loaded');
				}
			});
		}
	})
}

function showMyWindow(title, href, width, height, modal, minimizable,
		maximizable) {
	var h=document.body.clientHeight-50;
	$('#myWindow').window(
			{
				title : title,
				top : 0,
				left : 0,
				width : width === undefined ? 600 : width,
				height : h,//height === undefined ? 400 : height,
				content : '<iframe scrolling="yes" frameborder="0"  src="'
						+ href + '" style="width:100%;height:98%;"></iframe>',
				// href: href === undefined ? null : href,
				modal : modal === undefined ? true : modal,
				minimizable : minimizable === undefined ? false : minimizable,
				maximizable : maximizable === undefined ? false : maximizable,
				shadow : false,
				cache : false,
				closed : false,
				collapsible : false,
				resizable : false,
				loadingMessage : '正在加载数据，请稍等片刻......'
			});
}

function closeMyWindow(id) {
	$('#myWindow').window('close');
}

function closeAndRefresh(id) {
	$('#myWindow').window('close', true);
	loadDataGrid(id);
}

function showMsg(title, msg, isAlert) {
	if (isAlert !== undefined && isAlert) {
		$.messager.alert(title, msg);
	} else {
		// $.messager.show({
		// title: title,
		// msg: msg,
		// showType: 'show'
		// });
		showBySite(title, msg);
	}
}

function showBySite(title, msg) {
	$.messager.showBySite({
		title : title,
		msg : msg,
		showType : 'slide'// slide,fade

	}, {
		top : 0,// 将$.messager.show的top设置为点击对象之下
		left : (document.body.clientWidth / 2) - 100, // 将$.messager.show的left设置为与点击对象对齐
		bottom : ""
	});
}

function deleteConfirm() {
	return showConfirm('温馨提示', '确定要删除吗?');
}
function showConfirm(title, msg, callback) {
	$.messager.confirm(title, msg, function(r) {
		if (r) {
			if (jQuery.isFunction(callback))
				callback.call();
		}
	});
}
function showProcess(isShow, title, msg) {
	if (!isShow) {
		$.messager.progress('close');
		return;
	}
	var win = $.messager.progress({
		title : title,
		msg : msg
	});
}

function reload() {
	$(theGridID).treegrid('reload');
}
function getChildren() {
	var node = $(theGridID).treegrid('getSelected');
	if (node) {
		var nodes = $(theGridID).treegrid('getChildren', node.classId);
	} else {
		var nodes = $(theGridID).treegrid('getChildren');
	}
	var s = '';
	for ( var i = 0; i < nodes.length; i++) {
		s += nodes[i].classId + ',';
	}
	alert(s);
}

function getSelected() {
	return $(theGridID).treegrid('getSelected');
}

function getChildrenFromId(id) {
	return $(theGridID).treegrid('getChildren', id);
}

function getParentFromId(id) {
	return $(theGridID).treegrid('getParent', id);
}

function findNodeById(id) {
	return $(theGridID).treegrid('find', id);
}

function collapse() {
	var node = $(theGridID).treegrid('getSelected');
	if (node) {
		$(theGridID).treegrid('collapse', node.classId);
	}
}
function expand() {
	var node = $(theGridID).treegrid('getSelected');
	if (node) {
		$(theGridID).treegrid('expand', node.classId);
	}
}
function collapseAll() {
	$(theGridID).treegrid('collapseAll');
}
function expandAll() {
	$(theGridID).treegrid('expandAll');
}
function expandTo(id) {
	$(theGridID).treegrid('expandTo', id);
	$(theGridID).treegrid('select', id);
}
function select(id) {
	$(theGridID).treegrid('select', id);
}